const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const tenantQuery = require('../../db/tenantQuery/tenantQuery')

//引入时间模块
const sd = require('silly-datetime');

//解析from
const multiparty = require('multiparty')
//存储文件 
const path = require('path');
const fs = require('fs');

//解析token
const {
    token_verify
} = require('../../config/jwt')

//引入scoket通知
const {
    sendSystemMessage_auth
} = require('../../notice/auditNotice')

//发起租客认证
router.post('/attestation', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId,
        openId
    } = token_verify(token); //申请者者ID
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/tenant')
    }) // 设置文件存储路径
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    form.parse(req, (err, msg, files) => {
        try {
            const houseId = msg['houseId'][0];
            const name = msg['name'][0];
            const sex = msg['sex'][0];
            const tel = msg['tel'][0];
            const email = msg['email'][0];
            const iamge = files['contract'][0];
            const newPath = form.uploadDir + "/" + iamge.originalFilename
            fs.renameSync(iamge.path, newPath)
            const url = ht + "://" + host + "/images/tenant/" + iamge.originalFilename;
            pool.query(tenantQuery.insert_tenant, [userId, houseId, name, sex, tel, email, url, time], (error, result) => {
                if (error) {
                    logger().error("发起认证请求失败: " + error);
                    res.json(Response.error("发起认证请求失败", null));
                } else {
                    const tenantId = result.insertId;
                    pool.query(tenantQuery.select_houseOwner_id, houseId, (error, result) => {
                        if (error) {
                            logger().error("发起认证请求失败: " + error);
                            res.json(Response.error("发起认证请求失败", null));
                            return;
                        } else {
                            const user_id = JSON.parse(JSON.stringify(result[0].user_id));
                            sendSystemMessage_auth(user_id, {
                                openId,
                                applicant: name,
                                message: "您有一则租客认证信息需处理",
                                time,
                                tenantId
                            });
                            res.json(Response.success("发起认证请求成功", null));
                        }
                    });
                }
            });
        } catch (error) {
            logger().error("发起认证请求失败: " + error);
            res.json(Response.error("发起认证请求失败", error));
        }
    })
});

//获取认证信息详细
router.get('/detailed', function (req, res) {
    const token = req.headers.authorization;
    const {
        role,
    } = token_verify(token);
    const tenantId = req.query.tenantId;
    if (role == 1) {
        pool.query(tenantQuery.select_tanant, tenantId, (error, result) => {
            if (error) {
                res.json(Response.error("获取租客认证详细信息失败", null));
                logger().error("获取租客认证详细信息失败: " + error);
            } else {
                const data = JSON.parse(JSON.stringify(result));
                res.json(Response.success("获取租客认证详细信息成功", data));
            }
        });
    } else {
        res.json(Response.error("仅登录后以业主身份可查看", null));
    }
})

//获取所有我的租客认证
router.get('/allAttestation', function (req, res) {
    const token = req.headers.authorization;
    const {
        role,
        userId
    } = token_verify(token);
    if (role == 1) {
        pool.query(tenantQuery.select_tanant_all, userId, (error, result) => {
            if (error) {
                res.json(Response.error("获取所有我的租客认证列表失败", null));
                logger().error("获取所有我的租客认证列表失败: " + error);
            } else {
                const data = JSON.parse(JSON.stringify(result));
                res.json(Response.success("获取所有我的租客认证列表成功", data));
            }
        });
    } else {
        res.json(Response.error("仅登录后以业主身份可查看", null));
    }
})

//处理租客认证
router.post('/handleAuth', function (req, res) {
    //身份鉴权
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token);
    const tenantId = req.body.tenantId;
    const status = req.body.status;
    pool.query(tenantQuery.select_houseOwner_userId, tenantId, (error, result) => {
        if (error) {
            logger().error("处理租客信息失败: " + error);
            res.json(Response.error("处理租客信息失败", null));
            return;
        } else {
            const _userId = JSON.parse(JSON.stringify(result[0].user_id));
            if (userId !== _userId) {
                res.json(Response.success("非本人无权限操作", null));
            } else {
                pool.query(tenantQuery.change_tanant_status, [status, tenantId], (error, result) => {
                    if (error) {
                        logger().error("处理租客信息失败: " + error);;
                        res.json(Response.error("处理租客信息失败", null));
                        return;
                    } else {
                        res.json(Response.success("处理租客信息成功", null));
                    }
                });
            }
        }
    });
})

//获取我的认证列表
router.get('/auth', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token);
    pool.query(tenantQuery.select_tanantByuserId, userId, (error, result) => {
        if (error) {
            res.json(Response.error("获取我的认证信息失败", null));
            logger().error("获取我的认证信息失败: " + error);
            return;
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取我的认证信息成功", data));
        }
    });
})

module.exports = router;